<?php
/**
 * Created by PhpStorm.
 * User: 吴登科
 * Date: 2018/10/12
 * Time: 15:15
 * 用户优惠券相关
 */

namespace Api\Controller;

use Think\Controller;
use think\Session;

class CouponController extends Controller
{
    public $customer_id = '';
    public $store_id = 0;

    /*
     * 初始化
     */
    public function _initialize()
    {
        if (session('?customer_id') && session('?STORE_ID')) {
            $this->customer_id = session('customer_id');//用户id
            $this->store_id = session('STORE_ID');//店铺id
        }
    }

    /**
     * 店铺优惠列表
     */
    public function storeCouponList()
    {
        $this->store_id = 2;
        $this->customer_id = '20181011094823781242';

        if ($this->customer_id) {
            $list = M('coupon')->where(['store_id' =>  $this->store_id])->select();
            if (!empty($list)) {
                $this->ajaxReturn(['state' => 1, 'msg' => '获取成功', 'data' => $list]);
            } else {
                $this->ajaxReturn(['state' => 0, 'msg' => '没有优惠券']);
            }
        } else {
            $this->ajaxReturn(['state' => -1, 'msg' => '对不起请登录']);
        }
    }

    /**
     * 用户领取优惠券
     */
    public function getCoupon()
    {
        $this->store_id = 2;
        $this->customer_id = '20181011094823781242';

        if ( $this->customer_id) {
            if (!empty($coupon_ids)) {
                foreach ($coupon_ids as $key => $value) {
                    $map['store_id'] = $this->store_id;
                    $map['customer_id'] =  $this->customer_id;
                    $map['coupon_id'] = $value;
                    $map['get_time']=time();
                    //判断是否重复领取优惠券
                    $check_coupon = M('user_coupon')->where(['store_id' => $this->store_id, 'customer_id' => $this->customer_id, 'coupon_id' => $value])->find();
                    if ($check_coupon) {
                        $this->ajaxReturn(['state' => -3, 'msg' => '已经领取过了']);
                    } else {
                        $row = M('user_coupon')->add($map);
                    }
                }
                if ($row) {
                    $this->ajaxReturn(['state' => 1, 'msg' => '领取成功']);
                }
            } else {
                $this->ajaxReturn(['state' => -2, 'msg' => '缺少参数请检查']);
            }
        } else {
            $this->ajaxReturn(['state' => -1, 'msg' => '对不起请登录']);
        }
    }

}